<template>
  <div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="addApplyDialogVisible"
      width="60%"
      center
      :close-on-click-modal="false"
      @closed="closedDialog"
    >
      <div>
        <el-steps
          :active="active"
          process-status="finish"
          align-center
          finish-status="success"
        >
          <el-step title="选择申请类别"></el-step>
          <el-step title="填写资源信息"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
      </div>
      <!-- 第一步 -->
      <div style="width: 50%; margin: 20px auto" v-if="active == 0">
        <el-form
          ref="applyInfo"
          :rules="applyInfoRules"
          :model="applyInfo"
          label-width="180px"
        >
          <el-form-item label="资源类别" prop="resourceTypeName">
            <el-select
              disabled
              v-model="applyInfo.resourceTypeName"
              placeholder="请选择资源类别"
            >
              <el-option
                v-for="resourceType in resourceTypeList"
                :key="resourceType.resourceTypeName"
                :label="resourceType.resourceTypeTitle"
                :value="resourceType.resourceTypeName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="false" label="申请数量" prop="applyCount">
            <el-input
              v-model="applyInfo.applyCount"
              placeholder="请填写申请数量"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="申请原因" prop="applyReason">
            <el-input
              v-model="applyInfo.applyReason"
              placeholder="请填写申请原因"
              :disabled="permissions[0] == 'admin' && page == 'audit'"
            ></el-input>
          </el-form-item>
          <el-form-item label="申请时间" prop="applyTime">
            <el-date-picker
              v-model="applyInfo.applyTime"
              type="daterange"
              :picker-options="pickerBeginDateBefore"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
            <el-button type="text" @click="usingLongTime">
              点我长期使用
            </el-button>
          </el-form-item>
          <el-form-item
            label="管理员备注"
            v-if="permissions[0] == 'admin' && page == 'audit'"
            prop="adminRemark"
          >
            <el-input
              v-model="applyInfo.adminRemark"
              placeholder="请填写备注"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- 第二步 -->
      <div style="width: 60%; margin: 20px auto" v-if="active == 1">
        <!-- 创建新的资源 -->
        <el-form
          ref="resourceEntityInfo"
          :model="resourceEntityInfo"
          label-width="180px"
        >
          <el-form-item
            v-for="item in resourceTypeEntityFieldList"
            :prop="item.resourceTypeFieldName"
            :label="
              item.resourceTypeFieldUnit != '' &&
              item.resourceTypeFieldUnit != null
                ? item.resourceTypeFieldTitle +
                  '(' +
                  item.resourceTypeFieldUnit +
                  ')'
                : item.resourceTypeFieldTitle
            "
            :key="item.resourceTypeFieldId"
            :rules="[
              {
                required: item.resourceTypeFieldRequired,
                message: '请完善' + item.resourceTypeFieldTitle + '信息',
              },
            ]"
          >
            <el-input
              v-if="item.resourceTypeFieldType != 'enum'"
              v-model="resourceEntityInfo[item.resourceTypeFieldName]"
              :placeholder="'请输入' + item.resourceTypeFieldTitle"
              :disabled="
                applyInfo.resourceTypeName == 'pm' && permissions[0] != 'admin'
              "
            ></el-input>
            <el-select
              v-else
              v-model="resourceEntityInfo[item.resourceTypeFieldName]"
              placeholder="请选择"
              :disabled="
                applyInfo.resourceTypeName == 'pm' && permissions[0] != 'admin'
              "
            >
              <el-option
                v-for="enumItem in item.enumItemList"
                :key="enumItem.enumItemId"
                :label="enumItem.enumItemValue"
                :value="enumItem.enumItemKey"
              ></el-option>
            </el-select>
            <span v-if="item.resourceTypeFieldTitle == '配置'">
              格式：核数(个)/内存(GB)/磁盘(GB) 如：4C/16GB/256GB
            </span>
            <span v-if="item.resourceTypeFieldName == 'ip'">
              IP地址由管理员分配后进行填写
            </span>
          </el-form-item>
        </el-form>
      </div>
      <!-- 第三步 -->
      <div style="width: 50%; margin: 20px auto" v-if="active == 2">
        <h1 align="center">{{ handleResult }}</h1>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addApplyDialogVisible = false">关闭</el-button>
        <el-button v-if="active == 1" @click="preStep">上一步</el-button>
        <el-button v-if="active == 0" type="primary" @click="nextStep">
          下一步
        </el-button>
        <el-button
          v-if="active == 1"
          type="primary"
          @click="handleAddOrUpdateApplyInfo"
        >
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as EnumApi from "@/api/enum";
  import * as MyApplyApi from "@/api/myApply";
  import * as ResourceTypeApi from "@/api/resourceType";
  import * as ResourceTypeEntityApi from "@/api/resourceTypeEntity";
  import * as ResourceTypeFieldApi from "@/api/resourceTypeField";
  import * as AuditApplyApi from "@/api/auditApply";
  import * as ResourceTypeEntityDataApi from "@/api/resourceTypeEntityData";
  import { dateFormat } from "@/utils/dateFormat";
  import { mapGetters } from "vuex";

  export default {
    data() {
      return {
        // 控制添加申请窗口显示与消失
        addApplyDialogVisible: true,
        // 弹窗标题
        dialogTitle: "添加申请信息",
        // 操作成功提示信息
        handleResult: "提交申请信息成功",
        // 分步表单显示
        active: 0,
        // 申请信息
        applyInfo: {
          resourceTypeName: "vm",
          applyCount: 1,
        },
        // 申请信息校验
        applyInfoRules: {
          applyType: [
            { required: true, message: "请选择申请方式", trigger: "change" },
          ],
          resourceTypeName: [
            { required: true, message: "请选择资源类别", trigger: "change" },
          ],
          applyCount: [
            { required: true, message: "请填写申请数量", trigger: "change" },
          ],
          applyReason: [
            { required: true, message: "请填写申请原因", trigger: "blur" },
          ],
          applyTime: [
            { required: true, message: "请选择申请时间", trigger: "blur" },
          ],
        },
        // 填写的动态字段信息
        resourceEntityInfo: {},

        // 资源类别列表
        resourceTypeList: [],
        // 资源类别下动态字段信息
        resourceTypeEntityFieldList: [],

        // 设置当前日期之前不可选
        pickerBeginDateBefore: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          },
        },
      };
    },

    props: ["addOrUpdate", "dialogVisible", "rowData", "page"],

    computed: {
      ...mapGetters({
        permissions: "user/permissions",
      }),
    },

    methods: {
      // 判断添加or修改操作
      handleAddOrUpdateApplyInfo() {
        this.$refs.resourceEntityInfo.validate((valid) => {
          if (valid) {
            this.judgeAddOrUpdate();
          }
        });
      },
      judgeAddOrUpdate() {
        if (this.addOrUpdate) {
          this.handleAddApplyInfo();
        } else {
          this.handleEditInfo();
        }
      },
      // 添加申请信息
      handleAddApplyInfo() {
        this.formatterDate();
        let param = {
          applyInfo: this.applyInfo,
          resourceCacheInfo: {
            resourceTypeName: this.applyInfo.resourceTypeName,
            resourceEntityInfo: JSON.stringify(this.resourceEntityInfo),
          },
        };
        MyApplyApi.addApplyInfo(param).then((res) => {
          this.showMessage(res);
          if (res.code == 200) {
            this.active = 2;
            if (this.page == "entityList") {
              this.$emit("refresh-list");
            }
            if (this.applyInfo.applyResourceId != 0) {
              let param = {
                resourceTypeEntityId: this.applyInfo.applyResourceId,
                status: "apply",
              };
              ResourceTypeEntityApi.updateResourceTypeEntityStatusById(
                param
              ).then((res) => {});
            }
          }
        });
      },
      // 修改信息弹窗
      handleEditInfoDialog(row) {
        this.addApplyDialogVisible = true;
        this.dialogTitle = "修改申请信息";
        this.handleResult = "修改申请信息成功";

        this.applyInfo = row;
        if (row.resourceCacheInfoId != 0) {
          MyApplyApi.getResourceCacheInfoById(
            parseInt(row.resourceCacheInfoId)
          ).then((res) => {
            this.resourceEntityInfo = JSON.parse(res.data.resourceEntityInfo);
          });
        }
        this.$set(this.applyInfo, "applyTime", [
          row.applyStartUseTime,
          row.applyEndUseTime,
        ]);
      },
      // 修改信息
      handleEditInfo() {
        this.formatterDate();
        let param = {
          applyInfo: this.applyInfo,
          resourceCacheInfo: {
            id: this.applyInfo.resourceCacheInfoId,
            resourceTypeName: this.applyInfo.resourceTypeName,
            resourceEntityInfo: JSON.stringify(this.resourceEntityInfo),
          },
        };
        MyApplyApi.updateApplyInfo(param).then((res) => {
          if (res.code == 200) {
            this.active = 2;
            if (this.permissions[0] == "admin" && this.page == "audit") {
              let data = {
                applyId: this.applyInfo.id,
                agree: true,
                remark: this.applyInfo.adminRemark,
              };
              this.handleAssignResource(data);
              if (
                this.applyInfo.resourceTypeName == "pm" &&
                this.applyInfo.applyResourceId != 0
              ) {
                let entityFieldValue = {
                  resourceTypeName: this.applyInfo.resourceTypeName,
                  resourceTypeEntityId: this.applyInfo.applyResourceId,
                };
                Object.keys(this.resourceEntityInfo).forEach((eachKey) => {
                  entityFieldValue.resourceTypeFieldName = eachKey;
                  entityFieldValue.resourceTypeEntityDataValue = this.resourceEntityInfo[
                    eachKey
                  ];
                  ResourceTypeEntityDataApi.updateResourceTypeEntityDataByEntityIdAndFieldName(
                    entityFieldValue
                  ).then((res) => {});
                });
              }
            } else {
              this.showMessage(res);
            }
          } else {
            this.$message.error(res.data);
          }
        });
      },
      // 处理日期参数
      formatterDate() {
        if (this.applyInfo.applyStartUseTime === this.applyInfo.applyTime[0]) {
          return;
        }
        this.$set(
          this.applyInfo,
          "applyStartUseTime",
          dateFormat(this.applyInfo.applyTime[0])
        );
        this.$set(
          this.applyInfo,
          "applyEndUseTime",
          dateFormat(this.applyInfo.applyTime[1])
        );
      },
      // 长期使用
      usingLongTime() {
        let applyTime = [
          new Date(),
          new Date("9999-12-31 00:00:00".replace(/-/g, "/")),
        ];
        this.$set(this.applyInfo, "applyTime", applyTime);
      },
      // 上一步
      preStep() {
        if (this.active-- < 0) {
          this.active = 0;
        }
      },
      // 下一步
      nextStep() {
        this.$refs.applyInfo.validate((valid) => {
          if (valid) {
            this.getResourceTypeEntityFieldList();
            if (this.active++ > 1) {
              this.active = 0;
            }
            if (this.applyInfo.applyResourceId != 0) {
              ResourceTypeEntityDataApi.getResourceTypeEntityDataByEntityId(
                this.applyInfo.applyResourceId
              ).then((res) => {
                res.data.forEach((value) => {
                  this.$set(
                    this.resourceEntityInfo,
                    value.resourceTypeFieldName,
                    value.resourceTypeEntityDataValue
                  );
                });
              });
            }
          }
        });
      },
      // 弹窗关闭
      closedDialog() {
        this.dialogTitle = "添加申请信息";
        this.handleResult = "提交申请信息成功";

        this.$emit("closed-dialog", false);

        this.applyInfo = {
          resourceTypeName: "vm",
        };
        this.resourceEntityInfo = {};
        this.active = 0;
      },

      // 分配资源
      handleAssignResource(data) {
        AuditApplyApi.assignResource(data).then((res) => {
          this.showMessage(res);
          if (res.code == 200) {
            if (this.applyInfo.applyResourceId != 0) {
              let param = {
                resourceTypeEntityId: this.applyInfo.applyResourceId,
                status: "using",
              };
              ResourceTypeEntityApi.updateResourceTypeEntityStatusById(
                param
              ).then((res) => {});
            }
          }
        });
      },

      // 展示处理结果信息
      showMessage(res) {
        if (res.code == 200) {
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
        }
      },

      // 获取资源类别列表
      getResourceTypeList() {
        ResourceTypeApi.getResourceTypeList().then((res) => {
          this.resourceTypeList = res.data;
        });
      },
      // 获取资源类别实体字段列表
      getResourceTypeEntityFieldList() {
        ResourceTypeFieldApi.getResourceTypeFieldByName(
          this.applyInfo.resourceTypeName
        ).then((res) => {
          this.resourceTypeEntityFieldList = res.data;
          this.resourceTypeEntityFieldList.forEach((fieldInfo) => {
            if (fieldInfo.resourceTypeFieldType == "enum") {
              EnumApi.getEnumItemByGroupName(fieldInfo.enumGroupName).then(
                (res) => {
                  this.$set(fieldInfo, "enumItemList", res.data);
                }
              );
            }
          });
        });
      },
    },

    mounted() {
      this.getResourceTypeList();
      if (!this.addOrUpdate) {
        this.handleEditInfoDialog(this.rowData);
      }
      if (this.page == "entityList") {
        this.applyInfo = this.rowData;
        this.$set(this.applyInfo, "applyCount", 1);
      }
      if (this.page != "entityList" && this.page != "audit") {
        this.$set(this.applyInfo, "applyResourceId", 0);
      }
    },
  };
</script>
